#coding=utf-8
import sqlite3, re, os, sys, getopt, datetime
from support.utils.file.picture import Picture
from support.utils.dbms.db import DBHelper
from support.thread.task import Task
from support.ui.console import Log
from support.ui.board.dashboard import DashBoard

SUPPORT_FILE_TYPE = ['.jpeg','.png','.jpg','.mp4','.mov']
def printHelpInfo():
    print("幫助信息\n\n")
    print("usage: python {} [options] [db options]\n".format(sys.argv[0]))
    print("options:\n")
    print("-p\t : 从什么路径导入\n")
    print("-d\t : 保存在什么目录\n")
    print("-h\t : 帮助信息，与--help等效\n")
    print("-s\t : 过滤日志内容\n")
    print("-x\t : 使用UI图形界面\n\n")
    print("db options:\n")
    print("--dbpath\t : 数据库存放路径，默认为脚本所在目录\n")
    print("--dbname\t : 数据库名字，默认为myalbum.db\n")

def copyMediaFiles(src, dst, task):
    with task:
        pic = Picture(task)
        helper = DBHelper(dbpath, dbname)
        Log.i(__file__, "copy start")
        for path, dirlist, files in os.walk(src, followlinks=False):
            for file in files:
                subfile = os.path.join(path, file)
                if(os.path.isfile(subfile) and os.path.splitext(subfile)[-1].lower() in SUPPORT_FILE_TYPE):
                    task.updateProgress(total=1)
                    meta = pic.getMetaData(subfile, [Picture.KEY_GPS, Picture.KEY_WIDTH, Picture.KEY_HEIGHT, Picture.KEY_DATE])
                    ret = helper.query(DBHelper.TABLE_ALBUM, DBHelper.HASH, meta[Picture.HASH])
                    if(not ret):
                        Log.i(__file__, subfile, "is a new file")
                        _id = helper.insert(DBHelper.TABLE_ALBUM, {DBHelper.NAME:file, DBHelper.HASH:meta[Picture.HASH]})
                        helper.insert(DBHelper.TABLE_PICTURE, {DBHelper.ID:_id, DBHelper.WIDTH:pic.getData(meta,Picture.WIDTH), DBHelper.HEIGHT:pic.getData(meta,Picture.HEIGHT), DBHelper.DATE:pic.getData(meta,Picture.DATE)})
                        date = datetime.datetime.strptime(meta[Picture.DATE],  '%Y:%m:%d %H:%M:%S')
                        dstdir = os.path.join(dst, str(date.year), str(date.month), str(date.day))
                        task.submitJobsTask(func=pic.copy,  args=(subfile, dstdir), description=file, total=pic.getSize(subfile))
                    else:
                        Log.i(__file__, "skip", file)
                        task.updateProgress(advance=1)
        helper.close()
        task.waitAllFinished()


if __name__ == "__main__":
    opts,args = getopt.getopt(sys.argv[1:], '-s:-h-p:-d:-x', ["help","dbpath=","dbname=","maxqueue="])
    importfrom = None
    savepath = None
    dashboard = None
    dbpath = os.path.dirname(os.path.abspath(__file__))
    dbname = "myalbum.db"
    maxqueue = 20
    Log.Level = Log.DEBUG
    #Log.Mode = Log.MODE_SYSTEM
    if(not opts):
        printHelpInfo()
        sys.exit()
    for opt_name, opt_value in opts:
        if(opt_name in ('-h','--help')):
            printHelpInfo()
            sys.exit()
        elif(opt_name == '-x'):
            dashboard = DashBoard("Multimedia File Synchronizer")
        elif(opt_name == '-s'):
            Log.TAG_FILTER = opt_value
        elif(opt_name == '-p'):
            importfrom = opt_value
        elif(opt_name == '-d'):
            savepath = opt_value
        elif(opt_name == '--dbpath'):
            dbpath = opt_value
        elif(opt_name == '--dbname'):
            dbname = opt_value
        elif(opt_name == '--maxqueue'):
            maxqueue = int(opt_value)
    copyTask = Task(maxqueue=maxqueue, dashboard=dashboard)
    copyMediaFiles(importfrom, savepath if savepath is not None else dbpath, copyTask)
    Log.i(__file__, 'all task completed!')
    copyTask.submitJobsTask(func=copyMediaFiles, args=(importfrom, savepath if savepath is not None else dbpath))
